import router from '@/router'
import store from '@/store'
import request from '@/utils/request'
import { viewConfig } from "@/utils/coreConfig";
import { Message, MessageBox, Loading } from 'element-ui';
import { checkForm, getQueryObject, buildPDFPreviewUrl } from '../utils/index'
import showPopEvent from '../components/popEvent/index';
import showMessageboxEvent from '../components/messageBoxEvent/index';
import showChoiceTree from '../components/choiceTree/index';
import showChoiceOrg from '../components/choiceOrg/index';
import showChoicePerson from "../components/choicePerson/index";
import showChoiceGwmb from "../components/choiceGwmb/index";
import showChoiceNotion from "../components/choiceNotion/index";
import showTrackingModel from "../components/trackingModel/index";
import showBackRedoModel from "../components/BackRedoModel/index";
import showReturnDocModel from "../components/ReturnDocModel/index";
import showReleaseModal from "../components/ReleasaModel/index";
import showFlowSendModel from '../components/FlowSendModel/index';
import showAttachmentModel from '../components/attachmentModel/index';
import showChoiceFwh from '../components/choseFwh/index';
import showDjQjckModel from '../components/qjckModel/index';
import showDjCommentModel from '../components/commentModel/index';
import showRankODP from '../components/rankODP';
import showCustomFields from '../components/customFields/index'
import showAssessRank from '../components/assessRank/index';
import { getYb, getCurrentFlowCount, writeNotionWithImage } from "../api/common/flowsend";
import { bbglPrint } from "../api/module/bbgl/bbgl";
import { endProcess } from "../api/common/endProcess";
import { getNodeId } from "../api/common/getNodeId";
import filePreview, { fileQyPreview } from "../utils/filePreview";
import showBarCode from '../components/barCodeModel';
import { createByFile } from "../api/system/qiyuesuo/index";
import * as imageConversion from "image-conversion"
import { getList as getBwgzList } from "../api/common/bwgzApi";
import
{
    sendDoc,
    getSendFlowNode
} from "../api/common/flowsend";
import
{
    saveKingSignatrue,
    deleteKingSignatrueBySignatureId,
    updateKingSignatrueBySignatureId,
    getKingSignatrueListByDocumentId
} from "../api/system/kingSigns/index";
import
{
    getList as getFileDataList,
    getDownloadUrl as getFileDataDownloadUrl,
    getZBDownloadUrl,
    convertOFD
} from "../api/common/filedata";
import
{
    getList as getWordFilesList,
    getDownloadUrl,
    downWordFile,
} from "../api/common/wordfiles";
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
import { openUpload, getWordPreviewUrl } from "../api/common/attachment";
import drawQrcode from '../components/drawQrcode/index';
let VUE_APP_BASE_API = localStorage.getItem("local_server_ip") || window.HC_config.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API;

let isUserWPS = window.HC_config.VUE_APP_isInstallWps || false;

export const eventClickJs = {
    Message,
}

/**
 * cs 2022-3-9
 * 处理 按钮事件映射传参
 * @param params 事件的映射 键值对 {tableName: "@tableName"}
 * @param record 数据[Array,Object,String]
 */
export function getParamsObjByEvenetParams(params, record)
{
    if (!params)
    {
        return {};
    }
    let tampObj = {};
    if (record && record.constructor === Object)
    {
        console.log(params)
        //对象
        Object.keys(params).forEach((key) =>
        {
            if (
                params[key] &&
                params[key].constructor === String &&
                params[key].indexOf("@") == 0
            )
            {
                //@FormData.xh 获取子表单中的id
                let gainKey = params[key].replace("@", "");
                let gainKeyArr = gainKey.split(".");
                let value = getValueByKey(gainKeyArr, record);
                if (value != null && value != undefined)
                {
                    tampObj[key] = value;
                }
                else
                {
                    tampObj[key] = params[key];
                }
            }
            else
            {
                tampObj[key] = params[key];
            }

            //对paramsMap 属性进行深度解析
            if (key == "paramsMap" || key == "formParams" || key == "queryMap" || key == "paramsmap" || key == "formparams" || key == "querymap" || key == "chartParams" || key == "chartparams" || key == "m_ParamsMap" || key == "m_formparams" || key == "tabParams" || key == "params" || key == "containerParams" || key == "containerparams")
            {
                let paramValue = params[key];
                if (paramValue && typeof paramValue == "string")
                {
                    //JSON字符串 解析
                    try
                    {
                        let paramValueObj = JSON.parse(paramValue);
                        tampObj[key] = getParamsObjByEvenetParams(
                            paramValueObj,
                            record
                        );
                    } catch (e) { }
                } else if (paramValue && typeof paramValue == "object")
                {
                    //对象
                    console.log(paramValue);
                    tampObj[key] = getParamsObjByEvenetParams(paramValue, record);
                }
            }
            if (params[key] == "@FormData")
            {
                tampObj = record;
            }

            if (params[key] === "@CheckedFormData")
            {
                // 做表单验证
                tampObj = record;
                //需要做表单校验
                tampObj.needCheck = true;
            }
            if (params[key] === "@backlogUrl")
            {
                tampObj[key] = window.location.pathname;
            }
        });
    } else if (record && record.constructor === Array && record.length > 0)
    {
        Object.keys(params).forEach((key) =>
        {
            let paramValue = params[key];
            //兼容以前数据格式 @unids 取 多条 unid
            paramValue = paramValue == "@unids" ? "@unid" : paramValue;
            //数组
            tampObj[key] = [];

            record.forEach((recordItem) =>
            {
                if (
                    paramValue &&
                    paramValue.constructor === String &&
                    paramValue.indexOf("@") == 0
                )
                {
                    let tempValue = recordItem[paramValue.replace("@", "")];
                    if (tempValue)
                    {
                        tampObj[key].push(tempValue);
                    }
                } else
                {
                    let tempValue = params[key];
                    if (tempValue)
                    {
                        tampObj[key].push(tempValue);
                    }
                }
            });
            //以逗号拼接 需要unid 的才拼接
            // if (key == "unids" || paramValue == "@unid") {
            //     tampObj[key] = tampObj[key].join(",");
            // } else
            if (
                key == "paramsMap" || key == "formParams" || key == "queryMap" || key == "paramsmap" || key == "formparams" || key == "querymap" || key == "chartParams" || key == "chartparams" || key == "m_ParamsMap" || key == "m_formparams" || key == "tabParams" || key == "params" || key == "containerParams" || key == "containerparams"
            )
            {
                //深度解析
                let paramValue = params[key];
                if (paramValue && typeof paramValue == "string")
                {
                    //JSON字符串 解析
                    try
                    {
                        let paramValueObj = JSON.parse(paramValue);
                        tampObj[key] = getParamsObjByEvenetParams(
                            paramValueObj,
                            record
                        );
                    } catch (e)
                    {

                        console.log(e)
                    }
                } else if (paramValue && typeof paramValue == "object")
                {
                    //对象
                    tampObj[key] = getParamsObjByEvenetParams(params, record);
                }
            } else if (key == "formType" || key == "moduleName" || key == "viewType" || key == "fileName")
            {
                tampObj[key] = tampObj[key].length > 0 ? tampObj[key][0] : null;
            } else
            {
                paramValue = paramValue + "";
                // tampObj[key] = tampObj[key].join(",");
                //存在@ 才做数组拼接 否则都能等于原值
                if (paramValue.indexOf("@") == 0)
                {
                    tampObj[key] = tampObj[key].length > 0 ? tampObj[key].join(",") : paramValue;
                } else
                {
                    tampObj[key] = paramValue;
                }
                // tampObj[key] = tampObj[key].length > 0 ? tampObj[key].join(",") : null;
            }

            if (paramValue == "@selectedRows")
            {
                tampObj = record;
            }
        });
    } else if (record && record.constructor === String)
    {
        //字符串
        Object.keys(params).forEach((key) =>
        {
            let curValue = params[key];
            if (curValue && curValue.indexOf("@") == 0)
            {
                tampObj[key] = record;
            }
            else
            {
                tampObj[key] = curValue;
            }
        });
    } else
    {
        // 空不处理
        tampObj = params;
    }
    return tampObj;
}

/**
 * cs 2022-10-8
 * 编辑正文
 * @param {*} popParams
 * @param {*} res
 */
function editDoc(popParams, res)
{
    //文件没有被锁
    let hiddenBtnList = "";
    if (popParams.flowButtonState.btnZhiBan === false)
    {
        hiddenBtnList = ",btnInsertRedHeader";
    }
    if (!window.HC_config.VUE_APP_HCGZ)
    {
        hiddenBtnList += ",btnInsertSeal";
    }
    if (!window.HC_config.VUE_APP_isSaveAsToLocal)
    {
        hiddenBtnList += ",btnSaveAsFile";
    }

    let ShowRevision = false;
    if (popParams.flowButtonState.XxMrxh === true)
    {
        ShowRevision = true;
    }
    let item;
    console.log("-------签章------------")
    console.log(popParams.sealData);
    console.log("-------签章------------")
    //是否
    if (popParams.isCurrentFlow || !popParams.unid)
    {
        if (res.result && res.result.data.length > 0)
        {
            item = res.result.data[res.result.data.length - 1];

            editGwDocV2(
                VUE_APP_BASE_API,
                "",
                item.unid,
                popParams.unid,
                "",
                "",
                popParams.bookmark,
                hiddenBtnList,
                popParams.moduleName,
                store.getters.userInfo.personCommonname,
                ShowRevision,
                popParams.ycHongTou,
                popParams.sealData,
                popParams.flowData ? popParams.flowData.redHeaderUnid : undefined,
                store.getters.userInfo.unid,
                popParams.fwwh_fwz
            );
        } else
        {
            editGwDocV2(
                VUE_APP_BASE_API,
                "",
                "",
                popParams.unid,
                "",
                "",
                popParams.bookmark,
                hiddenBtnList,
                popParams.moduleName,
                store.getters.userInfo.personCommonname,
                ShowRevision,
                popParams.ycHongTou,
                popParams.sealData,
                popParams.flowData ? popParams.flowData.redHeaderUnid : undefined,
                store.getters.userInfo.unid,
                popParams.fwwh_fwz
            );
        }
    } else
    {
        if (res.result && res.result.data.length > 0)
        {
            item = res.result.data[res.result.data.length - 1];
            editGwDocV2(
                VUE_APP_BASE_API,
                "",
                item.unid,
                popParams.unid,
                "",
                "",
                popParams.bookmark,
                hiddenBtnList,
                popParams.moduleName,
                store.getters.userInfo.personCommonname,
                ShowRevision,
                popParams.ycHongTou,
                popParams.sealData,
                popParams.flowData ? popParams.flowData.redHeaderUnid : undefined,
                store.getters.userInfo.unid,
                popParams.fwwh_fwz
            );
        } else
        {
            Message.info("很抱歉，该文件没有正文");
        }
    }
}

/**
 * cs 2024-9-30
 * 打开wps在线编辑链接
 */
export function openWpsOnlineLink(unid, moduleName, permission, iszb)
{
    let requestParams = {
        url: "/v1/3rd/getWordEditUrl",
        method: "get",
        params: {
            unid: unid,
            moduleName: moduleName,
            permission: permission,
            iszb: iszb
        }
    };

    //执行请求
    request(requestParams).then(res =>
    {
        if (res.result && res.result.link)
        {
            window.open(res.result.link, "_blank");
        }
    })
}

/**
 * cs 2022-6-23
 * 合并新旧选中值
 *
 * @param {*} newRecord 新值
 * @param {*} oldRecord 旧值
 */
export function combineRecord(newRecord, oldRecord)
{
    if (!oldRecord)
    {
        return newRecord;
    }
    if (!newRecord)
    {
        return oldRecord;
    }

    let newType = newRecord.constructor;
    let oldType = oldRecord.constructor;
    //旧值是数组 且length 不为1 覆盖
    if (oldType === Array && oldRecord.length != 1)
    {
        return newRecord;
    }
    //新值是数组 且length 不为1 覆盖
    if (newType === Array && newRecord.length != 1)
    {
        return newRecord
    }

    //新值 旧值都为对象 融合
    if (newType === Object && oldType === Object)
    {
        let tampObj = { ...oldRecord, ...newRecord };
        return tampObj;
    }

    //新值为数组但只有一项 旧值都为对象 融合
    if (newType === Array && newRecord.length == 1 && oldType === Object)
    {
        let tampObj = { ...oldRecord, ...newRecord[0] };
        return tampObj;
    }


    //旧值为数组但只有一项 新值都为对象 融合
    if (oldType === Array && newRecord.length == 1 && newType === Object)
    {
        let tampObj = { ...oldRecord[0], ...newRecord };
        return tampObj;
    }

    //旧值为数组但只有一项 新值都为数组 但只有一项 融合
    if (oldType === Array && newRecord.length == 1 && newType === Array && newRecord.length == 1)
    {
        let tampObj = { ...oldRecord[0], ...newRecord[0] };
        return tampObj;
    }
    newRecord.del_flag = 0;
    return newRecord;
}

/**
 * 获取值根据属性列表
 * @param {*} P_KeyArr 属性列表
 * @param {*} P_Record 对象
 */
function getValueByKey(P_KeyArr, P_Record)
{
    let valueToReturn = null;
    if (P_KeyArr.length == 0)
    {
        return;
    }
    valueToReturn = P_Record;
    for (let i = 0; i < P_KeyArr.length; i++)
    {
        let tempKey = P_KeyArr[i];
        valueToReturn = valueToReturn[tempKey];
        if (valueToReturn == null || typeof valueToReturn != "object")
        {
            break;
        }
    }
    return valueToReturn;
}


/**
   * 初始化金格盖章
   */
function initKingGrid(P_Documentid)
{
    Signature.init({//初始化属性
        keysn: '2020082400059',//高法
        // keysn: 'T001',//测试
        certType: 'server',//设置证书在签章服务器
        sealType: 'server',//设置印章从签章服务器取
        serverUrl: 'http://144.20.3.153:8089/iSignatureHTML5/html5',// 高法
        // serverUrl: 'http://demo.kinggrid.com/iSignatureHTML5/html5',// 测试
        documentid: P_Documentid,//设置文档ID documentid:'KG2021041301'
        documentname: P_Documentid,//设置文档名称
        LANGUAGE: 'zh_CN',//语言设置
        autoCertMode: false,
        pw_timeout: 's1800', //s：秒；h:小时；d:天
        showProtectedBtn: true  //设置是否显示保护项按钮
    });

    Signature.bind({
        remove: function (fn)
        {//签章数据撤销时，将回调此方法，需要实现签章数据持久化（保存数据到后台数据库）,
            console.log('获取删除的签章ID：' + this.getSignatureid());
            deleteKingSignatrueBySignatureId({
                signatureId: this.getSignatureid()
            }).then(res =>
            {
                fn(true);//保存成功后必须回调fn(true/false)传入true/false分别表示保存成功和失败
            })
        },
        update: function (fn)
        {//签章数据有变动时，将回调此方法，需要实现签章数据持久化（保存数据到后台数据库）,执行后必须回调fn(true/false)，传入true/false分别表示保存成功和失败
            updateKingSignatrueBySignatureId({
                signatureId: this.getSignatureid(),
                signature: this.getSignatureData()
            }).then(res =>
            {
                fn(true);
            })
        }
    });

    let signatureCreator = Signature.create();
    console.log("-----创建成功-------")
    getKingSignatrueListByDocumentId({
        documentId: P_Documentid,
    }).then(res =>
    {
        let kingSigns = res.result || [];
        let signdata = new Array();
        kingSigns.forEach(pre_item =>
        {
            let map = {};
            map.signatureid = pre_item["signatureId"];
            map.signatureData = pre_item["signature"];
            signdata.push(map);
        })
        Signature.loadSignatures(signdata, null, function ()
        {

            console.log("---加载成功---")
            // var e = $("#pos0_div").find('.kg-img-div');
            // console.log(e);
        });
    })
    return signatureCreator;
}
/**
 * 金格手写签名
 */
function handWriteDlg(P_SignatureCreator, P_NotionType, P_Unid)
{

    P_SignatureCreator.handWriteDlg({
        image_height: "6.7",
        image_width: "5",
        onBegin: function ()
        {
            console.log('onbegin');
        },
        onEnd: function ()
        {
            console.log('onEnd');
        }
    }, function (param)
    {
        //alert(param.imageData);
        P_SignatureCreator.runHW(param, {
            protectedItems: [],//设置定位页面DOM的id，自动查找ID，自动获取保护DOM的kg-desc属性作为保护项描述，value属性为保护数据。不设置，表示不保护数据，签章永远有效。
            position: P_NotionType || "notionview",//设置盖章定位dom的ID，必须设置
            okCall: function (fn, image)
            {//点击确定后的回调方法，this为签章对象 ,签章数据撤销时，将回调此方法，需要实现签章数据持久化（保存数据到后台数据库）,保存成功后必须回调fn(true/false)渲染签章到页面上
                saveKingSignatrue({
                    documentId: P_Unid,
                    signatureType: P_NotionType,
                    signatureId: this.getSignatureid(),
                    signature: this.getSignatureData(),
                    imgData: image.imgdata,
                    imgName: image.name,
                    imgWidth: image.width,
                    imgHeight: image.height
                }).then(res =>
                {
                    fn(true);
                }).catch(err =>
                {
                    fn(false);
                })
            },
            cancelCall: function ()
            {//点击取消后的回调方法
                console.log("取消！")
            }
        });
    });
}
//金格盖章
function handleKingGrid(P_SignatureCreator, P_NotionType, P_Unid)
{
    P_SignatureCreator.run({
        protectedItems: [],//设置定位页面DOM的id，自动查找ID，自动获取保护DOM的kg-desc属性作为保护项描述，value属性为保护数据。不设置，表示不保护数据，签章永远有效。
        position: P_NotionType || "notionview",//设置盖章定位dom的ID，必须设置
        autoCert: false,
        okCall: function (fn, image)
        {//点击确定后的回调方法，this为签章对象 ,签章数据撤销时，将回调此方法，需要实现签章数据持久化（保存数据到后台数据库）,保存成功后必须回调fn(true/false)渲染签章到页面上
            console.log("盖章ID：" + this.getSignatureid());
            console.log(fn)
            console.log(image)
            saveKingSignatrue({
                documentId: P_Unid,
                signatureType: P_NotionType,
                signatureId: this.getSignatureid(),
                signature: this.getSignatureData(),
                imgData: image.imgdata,
                imgName: image.name,
                imgWidth: image.width,
                imgHeight: image.height
            }).then(res =>
            {
                fn(true);
            }).catch(err =>
            {
                fn(false);
            })
        },
        cancelCall: function ()
        {//点击取消后的回调方法
            console.log("取消！")
        }
    });
}

/**
 * cs 2022-4-4
 * 拼接url
 * @param {*} url
 * @param {*} paramsObj
 */
function getUrlByObj(url, paramsObj)
{
    let tampArr = [];
    if (url && url.indexOf("?") == -1)
    {
        url += "?";
    }
    else
    {
        url += "&";
    }

    Object.keys(paramsObj).forEach((item, index) =>
    {
        tampArr.push(item + "=" + paramsObj[item]);
    });
    url += tampArr.join("&");
    return url;
}

/**
 * 下载文件
 * @param {*} data
 * @param {*} fileName
 * @returns
 */
export function download(data, fileName)
{
    if (!data)
    {
        return;
    }
    let url = window.URL.createObjectURL(new Blob([data]));
    let link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

/**
 * cs 2022-4-4 弹出表单或视图
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 * @returns
 */
function popEvent(event, cEvent, record, otherObj)
{
    console.log(event, cEvent, record, otherObj, "popEvent==========================cs")
    let popParams;
    // 事件属性（后端传递map类型，存储键值对，当前使用到的参数有buttonList，用来替换弹窗自带的按钮事件）
    let eventProps = {};
    if (cEvent.params)
    {
        popParams = getParamsObjByEvenetParams(
            cEvent.params,
            record
        );
    } else
    {
        popParams = {};
    }
    if (cEvent.eventProps)
    {
        eventProps = cEvent.eventProps;
    }

    let popConfig = {
        cEvent: cEvent,
        parentRecord: record,
        parentObj: otherObj,
        top: popParams.top,
        bottom: popParams.bottom,
        width: popParams.width,
        height: popParams.height,
        theadColor: popParams.theadColor || viewConfig.theadColor, //表头颜色
        columnAlign: popParams.columnAlign || viewConfig.columnAlign, //默认对齐方式
        hasFotter: popParams.hasFotter != undefined ? popParams.hasFotter == "false" ? false : true : viewConfig.hasFotter,
        hasFooter: popParams.hasFooter != undefined ? popParams.hasFooter == "false" ? false : true : viewConfig.hasFooter,
        isShowQuery: popParams.isShowQuery != undefined ? popParams.isShowQuery : viewConfig.isShowQuery,
        modalTitle: popParams.modalTitle || event.btnTitle || "新增",
        className: popParams.className,
        buttonList: eventProps.buttonList || [],
        autoClose: popParams.autoClose != undefined ? popParams.autoClose == "false" ? false : true : true,
    }
    console.log("popEvent==========================popParams", popParams)
    if (popConfig.autoClose)
    {
        //弹出表单或视图
        showPopEvent(popParams, popConfig).then(res =>
        {
            console.log("弹出表单或视图给回调事件的数据", res)
            //给回调事件的数据
            let callRecord;
            if (res.choiceList)
            {
                //视图选择数据
                callRecord = res.choiceList;
                // otherObj = {...otherObj, ...res.otherObj }
            } else if (res.formData)
            {
                callRecord = res.formData;
                //弹出表单修改 otherObj
                otherObj = { ...otherObj, ...res.otherObj, oldOtherObj: otherObj }
            }
            if (res.containerParams || res.paramsMap || res.formParams)
            {
                // otherObj.callParams = res.containerParams || res.paramsMap || res.formParams;
            }
            let curEvent;
            if (res.event)
            {
                curEvent = res.event;
            }
            if (curEvent && !cEvent.callback)
            {
                //执行回调事件
                clickEvent({ btnEvent: curEvent }, combineRecord(callRecord, record), otherObj);
            }
            else if (cEvent.callback)
            {
                //执行回调事件
                clickEvent({ btnEvent: cEvent.callback }, combineRecord(callRecord, record), otherObj);
            }
            //兼容旧的写法 2022-9-21 chenshuai
            let changeList = [];
            if (cEvent.params)
            {
                for (let k in cEvent.params)
                {
                    let preParasItem = cEvent.params[k];
                    if (preParasItem && preParasItem.indexOf("@") > -1)
                    {
                        changeList.push({
                            value: preParasItem,
                            fieldName: k
                        })
                    }
                }

                //前端构造改变控件事件
                if (changeList.length > 0)
                {
                    let callback = {
                        callback: null,
                        callbackParams: null,
                        eventActions: null,
                        eventName: null,
                        eventProps: changeList,
                        eventTargets: null,
                        eventType: "CONTROL_EVENT",
                        methodName: null,
                        subModuleEvent: null,
                    }
                    console.log("前端构造改变控件事件===========>", callback);
                    clickEvent({ btnEvent: callback },
                        combineRecord(callRecord, record),
                        otherObj
                    );
                }
            }

        })
    }
    else
    {
        //弹出表单或视图
        showPopEvent(popParams, popConfig);
    }

    return;
}

/**
 * cs 2022-4-4 链接跳转事件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 */

function linkEvent(event, cEvent, record, otherObj)
{
    console.log("文件预览", event, cEvent, record, otherObj);
    let linkParams;
    if (cEvent.eventProps)
    {
        linkParams = getParamsObjByEvenetParams(
            cEvent.eventProps,
            record
        );
    } else
    {
        linkParams = {};
    }
    if (event.isOpenNewWindow == true || (otherObj && otherObj.isOpenNewWindow))
    {
        if (window.HC_config.VUE_APP_OPENFORM)
        {
            let urlStr = '/buildform'
            // 打开新页面并只显示表单
            if (cEvent.eventProps && (cEvent.eventProps.formtype || cEvent.eventProps.formType))
            {
                linkParams.path = 'form'
            }
            else
            {
                linkParams.path = event.methodName;
            }
            // 拼接url
            urlStr = getUrlByObj(urlStr, linkParams);
            window.open(urlStr, "_blank");
        }
        else
        {
            let urlStr = event.methodName;
            for (var item in linkParams)
            {
                if (typeof linkParams[item] === 'object')
                {
                    linkParams[item] = JSON.stringify(linkParams[item])
                }
            }

            urlStr = getUrlByObj(urlStr, linkParams);
            if (urlStr.indexOf("http://") != -1 || urlStr.indexOf("https://") != -1)
            {
                window.open(urlStr, "_blank")
            }
            else
            {
                urlStr = window.location.origin + urlStr
                window.open(urlStr, "_blank")
            }
        }
    }
    else
    {
        if (
            event.methodName &&
            (event.methodName.indexOf("http://") != -1 ||
                event.methodName.indexOf("https://") != -1)
        )
        {
            //拼接url
            let urlStr = event.methodName;
            urlStr = getUrlByObj(urlStr, linkParams);
            window.open(urlStr, "_blank");
        } else
        {
            for (var item in linkParams)
            {
                if (typeof linkParams[item] === 'object')
                {
                    linkParams[item] = JSON.stringify(linkParams[item])
                }
            }
            // if (linkParams.formParams)
            // {
            //     linkParams.formParams = JSON.stringify(linkParams.formParams)
            // }
            // if (linkParams.paramsMap)
            // {
            //     linkParams.paramsMap = JSON.stringify(linkParams.paramsMap)
            // }
            if (cEvent.methodName == router.currentRoute.path && window.HC_config.VUE_APP_FSANDFORM)
            {
                if (otherObj.handleBack)
                {
                    otherObj.handleBack()
                }
                else
                {
                    //适配 需要动态 路由的情况,当外层methodName 为空 取内层的动态的methodName
                    router.push({
                        path: cEvent.methodName || linkParams.methodName,
                        query: linkParams
                    });
                }
            }
            else
            {
                //适配 需要动态 路由的情况,当外层methodName 为空 取内层的动态的methodName
                router.push({
                    path: cEvent.methodName || linkParams.methodName,
                    query: linkParams
                });
            }

        }
    }
}

/**
 * cs 2022-4-4 询问事件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 */
function messageboxEvent(event, cEvent, record, otherObj)
{

    let btnList = [];
    for (let i = 0; i < cEvent.buttonList.length; i++)
    {
        cEvent.eventActions[i].btnTitle = cEvent.buttonList[i];
        btnList.push(cEvent.eventActions[i]);
    }

    showMessageboxEvent({
        modalText: cEvent.messageContant,
        btnList: btnList,
        record: record,
        otherObj: otherObj,
    }, {
        modalTitle: cEvent.title,
    }).then(res =>
    {

    })
}

/**
 * cs 2024-7-15 消息提醒事件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 * @returns
 */
function messageEvent(event, cEvent, record, otherObj)
{
    let messageType = cEvent.messageType;
    Message({
        showClose: cEvent.isShowClose,
        message: cEvent.messageContant,
        type: cEvent.eventType,
        duration: cEvent.showTime,
        onClose: () =>
        {
            if (cEvent.callback)
            {
                clickEvent({ btnEvent: cEvent.callback },
                    record,
                    otherObj
                );
            }
        }
    })
}

/**
 * cs 2022-4-4 打开特定组件事件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 */
async function modalEvent(event, cEvent, record, otherObj)
{
    console.log(event, cEvent, record, otherObj, '556')
    if (cEvent.methodName && (cEvent.methodName == "ChoiceTree" || cEvent.methodName == "CHOSETREE_CUSTOM" || cEvent.methodName == "MODAL_CHOSETREE_CUSTOM"))
    {
        //打开自定义选择树
        let isMulti = cEvent.eventProps.multi || false;
        let treeList = cEvent.eventProps.treeList || [];
        let replaceFields = cEvent.eventProps.replaceFields || null;
        //数据回显
        let showData = [];
        if (cEvent.eventProps.showData)
        {
            showData = cEvent.eventProps.showData.split(",");
        }
        if (cEvent.callback && cEvent.callback.eventType == "CONTROL_EVENT" && replaceFields)
        {
            if (cEvent.callback.eventProps && typeof cEvent.callback.eventProps == 'object')
            {
                let idStr = null;
                cEvent.callback.eventProps.forEach(item =>
                {
                    if (item.value.indexOf(replaceFields.key || replaceFields.value) > -1)
                    {
                        idStr = record[item.fieldName];
                    }
                })
                if (idStr)
                {
                    showData = idStr.split(",");
                }
            }
        }
        showChoiceTree({
            showData: showData,
            treeList: treeList,
            replaceFields: replaceFields,
            multiple: isMulti,
        }, cEvent.eventProps)
            .then((res) =>
            {
                let { choiceData, replaceFields } = res;

                if (cEvent.callback)
                {
                    console.log("------执行改变前-------")
                    console.log(combineRecord(choiceData.length == 1 ? choiceData[0] : choiceData, record));
                    console.log("------执行改变前-------")

                    clickEvent({ btnEvent: cEvent.callback },
                        combineRecord(choiceData.length == 1 ? choiceData[0] : choiceData, record),
                        otherObj
                    );
                }
            })
            .catch((err) =>
            {

            });

    } else if (cEvent.methodName && (cEvent.methodName == "ChoicePerson" || cEvent.methodName == "CHOSEPERSON" || cEvent.methodName == "MODAL_CHOSE_PERSON"))
    {
        //数据回显
        let showData = [];
        if (cEvent.callback && cEvent.callback.eventType == "CONTROL_EVENT" && replaceFields)
        {
            if (cEvent.callback.eventProps && typeof cEvent.callback.eventProps == 'object')
            {
                let idStr = null;
                let nameStr = null;
                cEvent.callback.eventProps.forEach(item =>
                {
                    if (item.value.indexOf(cEvent.eventProps.value) > -1)
                    {
                        idStr = record[item.fieldName];
                    }
                    if (item.value.indexOf(cEvent.eventProps.label) > -1)
                    {
                        nameStr = record[item.fieldName];
                    }
                })
                if (idStr && nameStr)
                {
                    let idArr = idStr.split(",");
                    let nameArr = nameStr.split(",");
                    if (idArr.length == nameArr.length)
                    {
                        idArr.forEach((item, index) =>
                        {
                            showData.push({
                                unid: item,
                                personCommonname: nameArr[index]
                            })
                        })

                    }
                }
            }
        }

        //打开选择人员树
        let isMulti = cEvent.eventProps.multi || false;
        let replaceFields = cEvent.eventProps.replaceFields || null;
        showChoicePerson({
            showData: showData,
            replaceFields: replaceFields,
            multiple: isMulti,
        }, {})
            .then((res) =>
            {
                let { choiceData, replaceFields } = res;
                if (cEvent.callback)
                {
                    clickEvent({ btnEvent: cEvent.callback },
                        combineRecord(choiceData.length == 1 ? choiceData[0] : choiceData, record),
                        otherObj
                    );
                }

                //兼容旧的写法 2022-9-21 chenshuai
                if (cEvent.eventProps && cEvent.eventProps.label && cEvent.eventProps.value)
                {
                    //前端构造改变控件事件
                    let callback = {
                        callback: null,
                        callbackParams: null,
                        eventActions: null,
                        eventName: null,
                        eventProps: [
                            { value: "@" + replaceFields.label, fieldName: cEvent.eventProps.label },
                            { value: "@" + replaceFields.value, fieldName: cEvent.eventProps.value },
                        ],
                        eventTargets: null,
                        eventType: "CONTROL_EVENT",
                        methodName: null,
                        subModuleEvent: null,
                    }
                    clickEvent({ btnEvent: callback },
                        combineRecord(choiceData.length == 1 ? choiceData[0] : choiceData, record),
                        otherObj
                    );
                }
            })
            .catch((err) =>
            {

            });

    } else if (cEvent.methodName && (cEvent.methodName == "ChoiceOrg" || cEvent.methodName == "CHOSEORG" || cEvent.methodName == "ChoiceOrgan" || cEvent.methodName == "MODAL_CHOSE_ORG"))
    {
        //数据回显

        let showData = [];
        if (cEvent.callback && cEvent.callback.eventType == "CONTROL_EVENT" && replaceFields)
        {
            if (cEvent.callback.eventProps && typeof cEvent.callback.eventProps == 'object')
            {
                let idStr = null;
                let nameStr = null;
                cEvent.callback.eventProps.forEach(item =>
                {
                    if (item.value.indexOf(cEvent.eventProps.value) > -1)
                    {
                        idStr = record[item.fieldName];
                    }
                    if (item.value.indexOf(cEvent.eventProps.label) > -1)
                    {
                        nameStr = record[item.fieldName];
                    }
                })
                if (idStr && nameStr)
                {
                    let idArr = idStr.split(",");
                    let nameArr = nameStr.split(",");
                    if (idArr.length == nameArr.length)
                    {
                        idArr.forEach((item, index) =>
                        {
                            showData.push({
                                unid: item,
                                orgCommonname: nameArr[index]
                            })
                        })

                    }
                }
            }
        }
        if (cEvent.eventProps && typeof cEvent.eventProps == 'object')
        {
            let idStr = record[cEvent.eventProps.value]
            let nameStr = record[cEvent.eventProps.label];

            if (idStr && nameStr)
            {
                let idArr = idStr.split(',');
                let nameArr = nameStr.split(',');
                if (idArr.length == nameArr.length)
                {
                    idArr.forEach((item, index) =>
                    {
                        showData.push({
                            unid: item,
                            orgCommonname: nameArr[index]
                        })
                    })
                }
            }
        }
        console.log(showData, 'showData')

        //打开选择机构数
        let isMulti = cEvent.eventProps.multi || false;
        let replaceFields = cEvent.eventProps.replaceFields || null;
        let isShowfullName = cEvent.eventProps.fullname || false;
        let treeList = cEvent.eventProps.treeList || [];
        showChoiceOrg({
            showData: showData,
            replaceFields: replaceFields,
            multiple: isMulti,
        }, {
            treeList: treeList,
            isShowfullName: isShowfullName,
            defaultExpandAll: cEvent.eventProps.defaultExpandAll,
            expandKeys: cEvent.eventProps.expandKeys,
            checkStrictly: cEvent.eventProps.checkStrictly
        })
            .then((res) =>
            {

                let { choiceData, replaceFields } = res;
                if (cEvent.callback)
                {

                    if (choiceData[0] && choiceData[0].delFlag == false)
                    {
                        choiceData[0].delFlag = 0;
                    }

                    clickEvent({ btnEvent: cEvent.callback },
                        combineRecord(choiceData.length == 1 ? choiceData[0] : choiceData, record),
                        otherObj
                    );

                }
                //兼容旧的写法 2022-9-21 chenshuai
                if (cEvent.eventProps && cEvent.eventProps.label && cEvent.eventProps.value)
                {

                    //前端构造改变控件事件
                    let callback = {
                        callback: null,
                        callbackParams: null,
                        eventActions: null,
                        eventName: null,
                        eventProps: [
                            { value: "@" + replaceFields.label, fieldName: cEvent.eventProps.label },
                            { value: "@" + replaceFields.value, fieldName: cEvent.eventProps.value },
                        ],
                        eventTargets: null,
                        eventType: "CONTROL_EVENT",
                        methodName: null,
                        subModuleEvent: null,
                    }
                    clickEvent({ btnEvent: callback },
                        combineRecord(choiceData.length == 1 ? choiceData[0] : choiceData, record),
                        otherObj
                    );
                }
            })
            .catch((err) =>
            {

            });
    } else if (cEvent.methodName && (cEvent.methodName == "fwhModal" || cEvent.methodName == "FWHMODAL" || cEvent.methodName == "MODAL_FWWH"))
    {
        //办文跟踪
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }

        showChoiceFwh(popParams).then(res =>
        {
            let { gfwh, form } = res;
            let changeFileList = [];
            if (popParams.notShowLsh)
            {
                changeFileList = [
                    { value: form.fwz, fieldName: "fwwhFwz" },
                    { value: form.lsm, fieldName: "fwwhLsm" },
                    { value: form.nd, fieldName: "fwwhNd" }
                ]
            }
            else
            {
                changeFileList = [
                    { value: gfwh, fieldName: "fwwh" },
                    { value: form.fwz, fieldName: "fwwhFwz" },
                    { value: form.lsh, fieldName: "fwwhLsh" },
                    { value: form.lsm, fieldName: "fwwhLsm" },
                    { value: form.nd, fieldName: "fwwhNd" }
                ]
            }

            //前端构造改变控件事件
            let callback = {
                callback: {
                    callback: {
                        //刷新表单
                        callbackParams: null,
                        eventActions: null,
                        eventName: null,
                        eventProps: null,
                        eventTargets: null,
                        eventType: "MODAL_EVENT",
                        methodName: "RELOADFORM",
                        subModuleEvent: null,
                    },
                    //保存表单
                    callbackParams: null,
                    eventActions: null,
                    eventName: null,
                    eventProps: null,
                    eventTargets: null,
                    eventType: "MODAL_EVENT",
                    methodName: "SAVEFORM",
                    params: {},
                    path: null,
                    subModuleEvent: null,
                },
                callbackParams: null,
                eventActions: null,
                eventName: null,
                eventProps: changeFileList,
                eventTargets: null,
                eventType: "CONTROL_EVENT",
                methodName: null,
                subModuleEvent: null,
            }
            clickEvent({ btnEvent: callback },
                record,
                otherObj
            );
        })
    } else if (cEvent.methodName && (cEvent.methodName == "reloadForm" || cEvent.methodName == "RELOADFORM" || cEvent.methodName == "REQ_RELOADFORM"))
    {
        //刷新表单
        if (otherObj.reaLoadForm)
        {
            otherObj.reaLoadForm();
        }
        if (otherObj.oldOtherObj && otherObj.oldOtherObj.reaLoadForm)
        {
            otherObj.oldOtherObj.reaLoadForm();
        }
    } else if (cEvent.methodName && (cEvent.methodName == "BWTRACHING"))
    {
        //办文跟踪
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        popParams.modulename = record.modulename || popParams.methodName;
        // this.$refs.DocumentTrackingModel.showModal(params);
        showTrackingModel(popParams);
    }
    else if (cEvent.methodName && (cEvent.methodName == "NOTIONMODAL" || cEvent.methodName == "MODAL_NOTION"))
    {
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }

        //打开阅文意见弹窗
        showChoiceNotion(popParams, {
            onlyInput: popParams.onlyInput,
            autoOpenSignature: popParams.autoOpenSignature
        }).then(res =>
        {
            //刷新阅文意见
            otherObj.reaLoadNotionData(popParams.type);
            //因为发送事件中有保存,这里就不再重复保存了
            if (res.showSendFlowView || popParams.usercall)
            {
                // 打开送文框
                try
                {
                    clickEvent(cEvent.callback, record, otherObj);
                } catch (err)
                {

                }
            }
            else if (res.ismhsw)
            {
                otherObj.saveForm().then(async formRes =>
                {
                    //模糊送文
                    let sendDocParam = res.sendDocParam || {};
                    let flowNodeRes = await getSendFlowNode(sendDocParam.moduleName, sendDocParam.unid, sendDocParam.sslb);
                    let flowBranceOptions = flowNodeRes.result.nodes || [];
                    if (flowBranceOptions.length > 0)
                    {
                        let sendDocPeronsUnid = [];
                        res.sendDocPeronsList.forEach(pre_person =>
                        {
                            sendDocPeronsUnid.push(pre_person.unid);
                        })
                        //默认勾选第一项
                        let sendNodeName = flowBranceOptions[0].nodeName;
                        let targetNodesWithUserObj = {};
                        targetNodesWithUserObj[sendNodeName] = sendDocPeronsUnid;

                        if (sendDocPeronsUnid.length == 0)
                        {
                            Message.error("请选择发送人员");
                            return;
                        }
                        sendDocParam.targetNodesWithUser = JSON.stringify(targetNodesWithUserObj);
                    }
                    else
                    {
                        Message.error("未找到可发送节点");
                        return;
                    }

                    sendDoc(sendDocParam)
                        .then((sendRes) =>
                        {
                            Message.success("发送成功");
                            if (res.sendCallBack)
                            {
                                //发送完成后回调
                                clickEvent(res.sendCallBack, record, otherObj);
                            } else
                            {
                                router.go(-1);
                            }
                        })
                        .catch((err) =>
                        {
                            console.log(err);
                        })
                })
            }
            else if (res.isaibw)
            {
                popParams.notiontype = type;
                //AI办文 自动调用完成接口
                getYb(popParams).then((res) =>
                {
                    Message.success("已办成功");
                    router.go(-1);
                });
            }
            else
            {
                //保存表单
                otherObj.saveForm();
            }
        })

    }
    else if (cEvent.methodName && cEvent.methodName == "UPLOAD_NOTION")
    {
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }

        //上传意见
        let inputDom = document.createElement("input");
        inputDom.type = "file";
        inputDom.onchange = () =>
        {
            let file = inputDom.files[0];
            file2Base64(file, file.size).then(res =>
            {
                const base64 = res.split(',')[1];
                let notionParams = {
                    docIdent: popParams.unid,
                    notionContent: "",
                    moduleName: popParams.moduleName,
                    flowstructureunid: popParams.flowstructureunid,
                    sslb: "",
                    published: 1,
                    fileType: "",
                    notionType: popParams.type,
                    sourceClient: "网页端",
                    wtrUnid: store.getters.userInfo.unid,
                    isNew: true,
                    file: base64,
                };
                let fileType = file.type;
                if (fileType == "application/pdf")
                {

                    notionParams.fileType = 'pdf';
                }
                else
                {
                    notionParams.fileType = fileType.split("/")[1];
                }
                notionParams.isNew = true;
                writeNotionWithImage(notionParams)
                    .then(res =>
                    {
                        this.$message.success("上传阅文意见签写成功");
                        //刷新阅文意见
                        otherObj.reaLoadNotionData(popParams.type);
                    })
                    .catch(P_Error =>
                    {
                        console.error("[图片阅文意见接口异常]", P_Error);
                        //刷新阅文意见
                        otherObj.reaLoadNotionData(popParams.type);
                    });
            })
        }
        inputDom.click();
    }
    else if (cEvent.methodName && (cEvent.methodName == "SENDFLOW" || cEvent.methodName == "MODAL_SENDDOC"))
    {
        // 流程中发送

        // //发送按钮流程最后一个节点的提示语
        if (cEvent.eventProps.constructor === Object && cEvent.eventProps.hasOwnProperty("isLastNode"))
        {
            if (cEvent.eventProps.isLastNode == true)
            {
                Message.warning("当前为最后节点，无法发送，请联系管理员进行办结");
                return false;
            }
        }

        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }

        // 先查询有多少人在办理中
        if (popParams.bltj)
        {
            let flowCountRes = await getCurrentFlowCount(popParams);
            if (flowCountRes.result > 0)
            {
                Message.error("当前还有" + flowCountRes.result + "个人在办理中");
                return
            }
        }
        if (popParams.BtnQianYWYJ)
        {
            if (!popParams.notionType)
            {
                Message.warning("当前节点未设置意见类型!");
                return
            }
            let typeList = popParams.notionType.split(",");
            getNodeId({ unid: popParams.unid, type: typeList[0], gxyj: (sessionStorage.getItem('gxyj') == 'true') }).then((res) =>
            {
                if (res.result)
                {
                    otherObj.saveForm().then(res =>
                    {
                        showFlowSendModel(popParams).then(res =>
                        {
                            if (cEvent.callback)
                            {
                                // this.$refs.eventClickRef.clickEvent(this.formBase.sendCallback);
                                //发送完成后回调
                                clickEvent(cEvent.callback, record, otherObj);
                            } else
                            {
                                router.go(-1);
                            }
                        })
                    })
                } else
                {
                    Message.warning("请签署阅文意见后再发送");
                }
            });
        }
        else
        {
            otherObj.saveForm().then(res =>
            {
                showFlowSendModel(popParams).then(res =>
                {
                    if (cEvent.callback)
                    {
                        // this.$refs.eventClickRef.clickEvent(this.formBase.sendCallback);
                        //发送完成后回调
                        clickEvent(cEvent.callback, record, otherObj);
                    } else
                    {
                        router.go(-1);
                    }
                })
            })
        }

    }
    else if (cEvent.methodName && cEvent.methodName == "LDYBTZ")
    {
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }

        //领导已办通知
        //第一步 查询流程跟踪 确定要发送的领导
        let bwgzRes = await getBwgzList({
            pageSize: 1000,
            pageNo: 1,
            wjId: popParams.unid,
            modulename: popParams.moduleName
        })
        let tableData = bwgzRes.result.data || [];
        let targetNodesWithUser = {};
        targetNodesWithUser["主办部门"] = [];
        targetNodesWithUser["协办部门"] = [];

        tableData.forEach(pre_item =>
        {
            if (pre_item.flowStructureNodeIdent == "主办部门")
            {
                targetNodesWithUser["主办部门"].push(pre_item.ownerIdent);
            }
            if (pre_item.flowStructureNodeIdent == "协办部门")
            {
                targetNodesWithUser["协办部门"].push(pre_item.ownerIdent);
            }
        })
        if (targetNodesWithUser["主办部门"].length > 0 || targetNodesWithUser["协办部门"].length > 0)
        {
            //第二步调用发送接口
            const urlparam = {
                flowstructureunid: popParams.flowstructureunid,
                unid: popParams.unid,
                awakeMode: "1",
                // backlogUrl: this.moduleurl,
                bt: "",
                backlogUrl: window.location.pathname,
                finalizeUnFinishTasks: false,
                moduleName: popParams.moduleName,
                openBacklogTarget: "_blank",
                senderUser: "1",
                targetNodesWithUser: JSON.stringify(targetNodesWithUser),
                sslb: popParams.formType ? popParams.formType : "",
            };

            sendDoc(urlparam)
                .then((res) =>
                {
                    Message.success("发送成功");
                    if (cEvent.callback)
                    {
                        //发送完成后回调
                        clickEvent(cEvent.callback, record, otherObj);
                    } else
                    {
                        router.go(-1);
                    }
                })
                .catch((err) =>
                {
                    console.log(err);
                })
        }
        else
        {
            Message.warning("未找到已发送过的主办处室记录");
        }
    }
    else if (cEvent.methodName && (cEvent.methodName == "SAVEFORM" || cEvent.methodName == "REQ_SAVEFORM"))
    {
        // 保存表单
        if (otherObj.saveForm)
        {
            otherObj.saveForm().then(res =>
            {
                let searchStr = window.location.search;
                if (searchStr != null)
                {
                    let queryObj = getQueryObject(searchStr);
                    if (queryObj.callback == 1)
                    {
                        router.go(-1);
                        return;
                    }
                }

                //保存成功
                Message.success("保存成功");
                if (cEvent.callback)
                {
                    clickEvent(cEvent.callback, res, otherObj);
                } else if (res.saveCallback)
                {
                    clickEvent(res.saveCallback, record, otherObj);
                }
                else
                {
                    router.go(-1);
                }
            }).catch(err => { });
        }
    } else if (cEvent.methodName && (cEvent.methodName == "BACKREDOMODAL" || cEvent.methodName == "MODAL_BACKREDO"))
    {
        // 回收重办
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        showBackRedoModel(popParams).then(res =>
        {
            if (cEvent.callback)
            {
                clickEvent({ btnEvent: cEvent.callback },
                    record,
                    otherObj
                );
            }
        })
    } else if (cEvent.methodName && cEvent.methodName == "RETUTNDOCMODAL")
    {
        // 退回
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        showReturnDocModel(popParams).then(res =>
        {
            if (cEvent.callback)
            {
                clickEvent({ btnEvent: cEvent.callback },
                    record,
                    otherObj
                );
            }
        })
    } else if (cEvent.methodName && (cEvent.methodName == "YIBAN" || cEvent.methodName == "REQ_YIBAN"))
    {
        // 已办
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        }
        else
        {
            popParams = {};
        }
        getYb(popParams).then((res) =>
        {
            Message.success("已办成功");
            router.go(-1);
        });
    } else if (cEvent.methodName && (cEvent.methodName == "END" || cEvent.methodName == "REQ_END"))
    {
        //办结 定稿 签收
        const loading = Loading.service({
            lock: true,
            text: event.eventName + '中', //办结中 或定稿中
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
        });
        //办结 或定稿
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        if (window.HC_config.VUE_APP_FlowBtnName && window.HC_config.VUE_APP_FlowBtnName.finish == "已办")
        {
            //办结
            endProcess(popParams).then((res) =>
            {
                loading.close();
                Message.success("已办成功");
                router.go(-1);
            }).catch(err =>
            {
                loading.close();
            });
            return;
        }

        // 先查询有多少人在办理中
        getCurrentFlowCount(popParams).then(res =>
        {
            let currentFlowCount = res.result || 0;
            var addmsg = "";

            if (currentFlowCount > 0)
            {
                addmsg = "当前还有" + currentFlowCount + "个人在办理中，";
            }
            MessageBox.confirm(addmsg + "确定要定稿该文件吗?", '提示').then(res =>
            {
                // 保存表单 并且不跳转
                otherObj.saveForm().then(res =>
                {
                    // 如果是收文 或发文 或 签报管理、qjgl则生成pdf
                    if (!window.HC_config.VUE_APP_NOPDF && (popParams.moduleName == "fwgl" || popParams.moduleName == "swgl" || popParams.moduleName.indexOf("qjgl") != -1 || popParams.moduleName.indexOf("qbgl") != -1))
                    {
                        //生成pdf
                        uploadPdf(popParams).then(res =>
                        {
                            endProcess(popParams).then((res) =>
                            {
                                loading.close();
                                Message.success(event.eventName + "成功");
                                setTimeout(() =>
                                {
                                    // 刷新表单
                                    otherObj.reaLoadForm();
                                }, 1000);
                            });
                        }).catch(err =>
                        {
                            loading.close();
                        })
                    } else
                    {
                        //办结
                        endProcess(popParams).then((res) =>
                        {
                            loading.close();
                            Message.success(event.eventName + "成功");
                            setTimeout(() =>
                            {
                                // 刷新表单
                                otherObj.reaLoadForm();
                            }, 1000);
                        }).catch(err =>
                        {
                            loading.close();
                        });
                    }
                }).catch(err =>
                {
                    loading.close();
                })
            }).catch(err =>
            {
                loading.close();
            })

        }).catch(err =>
        {
            loading.close();
        })
    } else if (cEvent.methodName && (cEvent.methodName == "RELEASE" || cEvent.methodName == "MODAL_PUBLISH"))
    {
        // 发布
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        if (((record.zsdw && record.zsdwId) || (record.csdw && record.csdwId)))
        {
            popParams.zsdw = record.zsdw
            popParams.zsdwId = record.zsdwId
            popParams.csdw = record.csdw
            popParams.csdwId = record.csdwId
        }
        //发布
        showReleaseModal(popParams).then(res =>
        {

        })
    } else if (cEvent.methodName && (cEvent.methodName == "WRITEDOC" || cEvent.methodName == "REQ_OPEN_WEBADOPT"))
    {
        let isShowZWtip = 1;//是否显示正文提示
        let isShowZWtipCache = localStorage.getItem("VUE_APP_SHOWWRITEDOCTIP");
        if (isShowZWtipCache)
        {
            isShowZWtip = isShowZWtipCache;
        }
        if (window.HC_config.VUE_APP_SHOWWRITEDOCTIP && isShowZWtip == 1)
        {
            // 正文
            MessageBox.confirm('保存正文请在WPS中点击`OA辅助`下的按钮`保存到OA`', '提示', {
                distinguishCancelAndClose: true,
                showClose: false,
                closeOnClickModal: false,
                closeOnPressEscape: false,
                confirmButtonText: '我知道了',
                cancelButtonText: '我知道了,下次不再提醒'
            }).then(() =>
            {
                writeDoc(cEvent, record);
            }).catch(() =>
            {
                localStorage.setItem("VUE_APP_SHOWWRITEDOCTIP", 0);
                writeDoc(cEvent, record);
            })
        }
        else
        {
            writeDoc(cEvent, record);
        }
    }
    else if (cEvent.methodName && (cEvent.methodName == "REQ_MAKING"))
    {
        console.log(cEvent);
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        console.log(popParams);
        showChoiceGwmb(popParams, {}).then(res =>
        {
            let gwmbAttachMentUnid = res.choiceData[0].tempId;
            let bookmark = popParams.bookmark;
            let bookmarkArr = bookmark.split("($&$)");
            let bookmarkList = [];
            bookmarkArr.forEach(pre_bookmark =>
            {
                let bookmarkLabelValueArr = pre_bookmark.split("($:$)");
                if (bookmarkLabelValueArr.length == 2)
                {
                    let temp_Map = {
                        lable: bookmarkLabelValueArr[0],
                        value: bookmarkLabelValueArr[1]
                    }
                    bookmarkList.push(temp_Map);
                }
            })

            //发送制版请求
            request({
                url: "/v1/3rd/wordMaking",
                method: "post",
                data: {
                    wordFileUnid: popParams.docUnid,
                    gwmbFjUnid: gwmbAttachMentUnid,
                    bookmarkList: bookmarkList
                }
            }).then(res =>
            {
                //制版成功 跳转编辑制版正文页面
                //只读打开在线链接
                openWpsOnlineLink(popParams.unid, popParams.moduleName, "write", 1);
            })
        })
    }
    else if (cEvent.methodName && (cEvent.methodName == "ZhuanBanGaiZhang" || cEvent.methodName == "REQ_CONVERTANDSTAMP"))
    {
        //转版盖章
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        convertOFD(popParams.unid)
            .then((res) =>
            {
                let windowObj = window.open(
                    process.env.VUE_APP_PUBLIC_PATH + "zxfw/ofdgz.html?unid=" + popParams.unid
                );
                let loop = setInterval(function ()
                {
                    if (windowObj != null && windowObj.closed)
                    {
                        clearInterval(loop);
                        //直接刷新表单
                        otherObj.reaLoadForm();
                    }
                }, 800);
            })
            .catch((err) =>
            {
                Message.error("系统错误");
            });
    } else if (cEvent.methodName && (cEvent.methodName == "flowBtn5gKuaiQian" || cEvent.methodName == "REQ_5GKQ"))
    {
        //5G快签
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        //跳转到5G快签界面
        router.push({
            path: "/showpdf",
            query: {
                type: "5gKuaiQian",
                isGz: 1,
                unid: popParams.unid
            }
        })
    } else if (cEvent.methodName && (cEvent.methodName == "GaiZhang" || cEvent.methodName == "REQ_STAMP"))
    {
        //5G盖章
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        if (window.HC_config.VUE_APP_5G_GAIZHANG)
        {
            //跳转到5G快签界面
            router.push({
                path: "/signpdf",
                query: {
                    type: "5gKuaiQian",
                    isGz: 1,
                    unid: popParams.unid
                }
            })
        }
        else if (window.HC_config.VUE_APP_ISKINGGRID)
        {
            //金格电子签章
            let signatureCreator = initKingGrid(popParams.unid);
            if (popParams.isWrite)
            {
                handWriteDlg(signatureCreator, popParams.notionType, popParams.unid);
            }
            else
            {
                handleKingGrid(signatureCreator, popParams.notionType, popParams.unid);
            }
        }
        else if (window.HC_config.VUE_APP_ISQIYUESUO)
        {
            // 调用契约锁盖章
            console.log(popParams, "==========popParams=========")
            console.log("调用契约锁进行盖章！！！")
            createByFile({
                relationUnid: popParams.unid,
                bt: popParams.bt
            }).then(res =>
            {
                console.log(res, "================")
                window.open(res.result); // 打开电子签章的地址
                //定时器每3秒发送一次请求
                let interval = setInterval(function ()
                {
                    getGaiZhangDoc(popParams, interval, otherObj);
                }, 3000);
            });
        }
        else if (window.HC_config.VUE_APP_ISJINGGE)
        {

            getWordFilesList({
                parentUnid: popParams.unid,
            })
                .then((res) =>
                {
                    let item;
                    if (res.result && res.result.data.length > 0)
                    {
                        item = res.result.data[res.result.data.length - 1];
                        let herfLink = location.origin + "/iWebPDF2018/index.html?wordId=" + item.unid + "&parentUnid=" + popParams.unid
                        window.open(herfLink);

                        //定时器每3秒发送一次请求
                        let interval = setInterval(function ()
                        {
                            getGaiZhangDoc(popParams, interval, otherObj);
                        }, 3000);
                    }
                    else
                    {
                        Message.info("请先编辑正文");
                    }
                })
        }
        else if (window.HC_config.VUE_APP_ISCASIGN)
        {
            //北京CA电子签章
            getWordFilesList({
                parentUnid: popParams.unid,
            })
                .then((res) =>
                {
                    let item;
                    if (res.result && res.result.data.length > 0)
                    {
                        item = res.result.data[res.result.data.length - 1];
                        let herfLink = location.origin + "/pdfsign_web/index.html?wordId=" + item.unid + "&parentUnid=" + popParams.unid
                        window.open(herfLink);

                        //定时器每3秒发送一次请求
                        let interval = setInterval(function ()
                        {
                            getGaiZhangDoc(popParams, interval, otherObj);
                        }, 3000);
                    }
                    else
                    {
                        Message.info("请先编辑正文");
                    }
                })
        }
        else
        {
            if (typeof popParams.unid == "undefined")
            {
                return;
            }
            gaiZhangDoc(popParams, otherObj);
        }
    }
    else if (cEvent.methodName && cEvent.methodName == "UPLOAD_GZZW")
    {
        otherObj.saveForm().then(res =>
        {
            //上传盖章正文
            let params = getParamsObjByEvenetParams(cEvent.eventProps, record);
            let inputDom = document.createElement("input");
            inputDom.type = "file";
            inputDom.onchange = () =>
            {
                let file = inputDom.files[0];
                var formdata = new FormData();
                formdata.append("file", file);
                request({
                    url: "/gwfj/filedata/upload/" + params.unid,
                    method: "post",
                    params: params,
                    data: formdata,
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                })
                    .then((res) =>
                    {
                        if (otherObj.reaLoadForm)
                        {
                            otherObj.reaLoadForm(); //刷新表单 隐藏盖章按钮
                        }
                    })
            }
            inputDom.click();
        })
    }
    else if (cEvent.methodName && (cEvent.methodName == "GaiZhangCheck" || cEvent.methodName == "REQ_SHOW_STAMP"))
    {
        // 查看盖章正文
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        if (typeof popParams.unid == "undefined")
        {
            return;
        }
        checkDoc(popParams)
    }
    else if (cEvent.methodName && (cEvent.methodName == 'CHECKZW'))
    {
        // 查看盖章正文
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        if (typeof popParams.unid == "undefined")
        {
            return;
        }
        //查看正文
        if (popParams.hasGaiZhangDoc)
        {
            checkDoc(popParams)
        }
        else if (popParams.hasDoc)
        {
            writeDoc(cEvent, record);
        }
    }
    else if (cEvent.methodName && (cEvent.methodName == "DownGaiZhang" || cEvent.methodName == "REQ_DOWNLOAD_STAMP"))
    {
        // 下载盖章正文
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        //盖章正文列表
        let gzDocListRes = await getFileDataList({
            parentUnid: popParams.unid,
        })
        if (gzDocListRes.result && gzDocListRes.result.data.length > 0)
        {

            let openurl = getFileDataDownloadUrl(popParams.unid);
            window.open(openurl);
        }
        else
        {
            //没有盖章正文下载正文
            getWordFilesList({
                parentUnid: popParams.unid,
            }).then((res) =>
            {
                if (res.result && res.result.data.length > 0)
                {
                    var item = res.result.data[res.result.data.length - 1];
                    const url = getDownloadUrl(item.unid);
                    window.open(url);
                }
                else
                {
                    Message.info("很抱歉，该文件没有正文");
                }
            });
        }
    } else if (cEvent.methodName && (cEvent.methodName == "OPEMATTACHMENT" || cEvent.methodName == "MODAL_OPEN_ATTACHMENT"))
    {
        //附件
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }

        showAttachmentModel(popParams).then(res =>
        {
            //刷新表单
            otherObj.reaLoadForm();
        });

    } else if (cEvent.methodName && (cEvent.methodName == "DownZW" || cEvent.methodName == "REQ_DOWNLOAD_WEBADOPT"))
    {
        //下载正文
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        getWordFilesList({
            parentUnid: popParams.unid,
        }).then((res) =>
        {
            if (res.result && res.result.data.length > 0)
            {
                var item = res.result.data[res.result.data.length - 1];
                const url = getDownloadUrl(item.unid);
                window.open(url);
            }
        });
    } else if (cEvent.methodName && (cEvent.methodName == "PRINT" || cEvent.methodName == "REQ_PRINT"))
    {
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        //打印
        let bt = popParams.formType;
        const loading = Loading.service({
            lock: true,
            text: "打印中", //办结中 或定稿中
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
        });

        if (popParams.moduleName == "fwgl") bt = "发文处理单";
        if (popParams.moduleName == "swgl") bt = "收文处理单";
        if (popParams.moduleName == "wcgl") bt = "外出报备";
        if (popParams.moduleName == "ldrc") bt = "领导日程";
        if (popParams.moduleName == "qjgl") bt = "请假管理";
        if (popParams.moduleName == "clgl") bt = "车辆管理";
        if (popParams.moduleName == "xxsp") bt = "信息审批";
        if (popParams.moduleName == "qbgl") bt = "签报处理单";
        bbglPrint({ bt: bt, unid: popParams.unid, sslb: popParams.formType, modulename: popParams.moduleName })
            .then((res) =>
            {
                if (res.fieldName)
                {
                    let formTitle = res.fieldName;
                    let fileName = formTitle + ".docx";
                    if (res.data.type == "application/pdf")
                    {
                        fileName = formTitle + ".pdf";
                    }
                    download(res.data, fileName);
                } else
                {
                    let formTitle = bt;
                    let fileName = formTitle + ".docx";
                    if (res.type == "application/pdf")
                    {
                        fileName = formTitle + ".pdf";
                    }
                    download(res, fileName);
                }

            })
            .finally(() =>
            {
                loading.close();
            });
    } else if (cEvent.methodName && cEvent.methodName == "REQ_REALOADCOM")
    {
        //刷新表单中的视图、图表、tab
        if (otherObj.realoadCom)
        {
            if (cEvent.eventProps)
            {
                let eventParams = getParamsObjByEvenetParams(
                    cEvent.eventProps,
                    record
                );

                otherObj.realoadCom(eventParams.comtype || eventParams.comType, eventParams);

                //执行回调事件
                if (cEvent.callback)
                {
                    clickEvent({ btnEvent: cEvent.callback },
                        record,
                        otherObj
                    );
                }
            }
        }
    } else if (cEvent.methodName && cEvent.methodName == "Ckqjry")
    {
        // 党建活动中请假列表查看请假详情
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        console.log(popParams, '参数')
        showDjQjckModel(popParams).then(res =>
        {
            console.log(res)
        })
    } else if (cEvent.methodName && cEvent.methodName == 'pl')
    {
        console.log('党建评论')
        // 党建活动中评论弹出框
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        }
        else
        {
            popParams = {}
        }
        console.log(popParams, '参数')
        showDjCommentModel(popParams).then(res =>
        {
            console.log(res)
        })
    } else if (cEvent.methodName && (cEvent.methodName == "REQ_REALOAD"))
    {
        console.log(otherObj);
        if (cEvent.eventProps)
        {
            let comType = cEvent.eventProps.comType || cEvent.eventProps.comtype;
            let comParams = comType == 'form' ? cEvent.eventProps.formparams || cEvent.eventProps.formParams :
                comType == 'view' ? cEvent.eventProps.paramsmap || cEvent.eventProps.paramsMap :
                    comType == 'fs' ? cEvent.eventProps.params || cEvent.eventProps.containerparams || cEvent.eventProps.containerParams :
                        cEvent.eventProps;
            if (typeof (comParams) == 'string')
            {
                comParams = JSON.parse(comParams);
            }
            let eventParams = getParamsObjByEvenetParams(
                comParams,
                record
            );
            console.log(eventParams, "==============eventParams")
            if (comType == 'view' && otherObj.reaLoadView)
            {
                //刷新视图 视图的事件 会存在刷新视图的方法
                otherObj.reaLoadView();
            }
            if (comType == 'fs' && otherObj.reaLoadFs)
            {
                //刷新视图 fs视图的事件 会存在刷新fs视图的方法
                otherObj.reaLoadFs();
            }
            if (comType == 'form' && otherObj.reaLoadForm)
            {
                //刷新表单的事件 会存在刷新表单的方法
                otherObj.reaLoadForm(eventParams);
            }
        }

    } else if (cEvent.methodName && cEvent.methodName == "px")
    {
        // 党建排序
        console.log(cEvent, '排序')
        let isMulti = cEvent.eventProps.multi || false;
        let treeList = cEvent.eventProps.treeList || [];
        let replaceFields = cEvent.eventProps.replaceFields || null;

        showRankODP(
            {
                showData: null,
                treeList: treeList,
                replaceFields: replaceFields,
                multiple: isMulti
            }, {}
        ).finally(() =>
        {
            console.log('回调')
        })
    } else if (cEvent.methodName && cEvent.methodName == "REQ_FILEPREVIEW")
    {
        //文件预览
        let file;
        if (cEvent.eventProps)
        {
            file = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            file = {};
        }
        filePreview(file);
    } else if (cEvent.methodName && cEvent.methodName == "PRINT_HTML")
    {
        if (cEvent.eventProps && cEvent.eventProps.id)
        {
            // html转pdf
            let fill = null;
            html2Canvas(document.querySelector("#" + cEvent.eventProps.id), {
                allowTaint: true,
                useCORS: true, // canvas.toDataUrl() 图片跨域问题  添加这个设置
            }).then(function (canvas)
            {
                const contentWidth = canvas.width;
                const contentHeight = canvas.height;
                const pageHeight = (contentWidth / 592.28) * 841.89;
                let leftHeight = contentHeight;
                let position = window.HC_config.VUE_PDF_MARGIN_TOP || 0;
                const imgWidth = 595.28;
                const imgHeight = (592.28 / contentWidth) * contentHeight;
                const pageData = canvas.toDataURL("image/jpeg", 1.0);
                const PDF = new JsPDF("", "pt", "a4");
                if (leftHeight < pageHeight)
                {
                    PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
                } else
                {
                    while (leftHeight > 0)
                    {
                        PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
                        leftHeight -= pageHeight;
                        position -= 841.89;
                        if (leftHeight > 0)
                        {
                            PDF.addPage();
                        }
                    }
                }
                fill = PDF.output("datauristring");
                const filepdf = dataURLtoFile(
                    fill,
                    (cEvent.eventProps.bt || "") + (cEvent.eventProps.suffix || "处理单.pdf")
                );
                const formData = new FormData();
                formData.append("file", filepdf);
                formData.append("relationUnid", cEvent.eventProps.unid);
                formData.append("moduleName", cEvent.eventProps.modulename);
                formData.append("type", cEvent.eventProps.type);
                //上传
                openUpload(formData, (progress) =>
                {
                    // this.$emit("AttachmentViewProgressUpdate", progress);
                })
                    .then((res) =>
                    {
                        console.log(res, "================cs");
                        if (cEvent.callback)
                        {
                            clickEvent(cEvent.callback, res.result, otherObj);
                        }
                    })
                    .catch((error) =>
                    {

                    })
                    .finally(() => { });
            });
        }
    } else if (cEvent.methodName && cEvent.methodName == "REQ_IMPLANT")
    {
        //嵌入组件
        let P_ImplantParms = {};
        if (cEvent.eventProps)
        {
            P_ImplantParms = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            P_ImplantParms = {};
        }
        otherObj.implantCom(P_ImplantParms);
    } else if (cEvent.methodName && cEvent.methodName == 'bar-print')
    {
        showBarCode(record, {}).finally(() =>
        {
            console.log('回调')
        })
    } else if (cEvent.methodName && cEvent.methodName == 'CustomFields')
    {
        // 自定义视图字段
        console.log(otherObj._this.columns, '123')
        console.log(otherObj._this.allColumns, '123456')
        console.log(event, 'event')
        let modulename = ""
        let viewtype = ""
        if (event.eventProps)
        {
            modulename = event.eventProps.modulename || event.eventProps.moduleName
            viewtype = event.eventProps.viewtype || event.eventProps.viewType
        }
        else
        {
            modulename = event.params.modulename || event.params.moduleName
            viewtype = event.params.viewType || event.params.viewtype
        }
        let columns = otherObj._this.columns
        let allColumns = localStorage.getItem('viewColumns_' + modulename + '_' + viewtype) ? JSON.parse(localStorage.getItem('viewColumns_' + modulename + '_' + viewtype)) : otherObj._this.allColumns
        showCustomFields(
            {
                columns: columns,
                allColumns: allColumns
            }, {}
        ).then(res =>
        {
            console.log(res, '回调')
            let { resultData } = res
            localStorage.setItem('viewColumns_' + modulename + '_' + viewtype, JSON.stringify(resultData))
            if (otherObj.reaLoadView)
            {
                otherObj.reaLoadView()
            }
        })
    }
    else if (cEvent.methodName && cEvent.methodName == 'kytjechart')
    {
        // 科研年度考核排名
        showAssessRank({}, {}).then(res =>
        {
            console.log(res, '11')
        })
    }
    else if (cEvent.methodName && cEvent.methodName == 'QuanYue')
    {
        //圈阅
        let popParams;
        if (cEvent.eventProps)
        {
            popParams = getParamsObjByEvenetParams(
                cEvent.eventProps,
                record
            );
        } else
        {
            popParams = {};
        }
        let base_url = localStorage.getItem("local_server_ip") || window.HC_config.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API;
        let url = base_url + "/sign/contract/showFile/?unid=" + popParams.formUnid
        fileQyPreview({
            file: url,
            unid: popParams.formUnid,
            fileUnid: popParams.docUnid,
            fileName: popParams.fileName,
            formType: popParams.formType,
            moduleName: popParams.moduleName,
        })
    }
    else if (cEvent.methodName && cEvent.methodName == 'DRAWQRCODE')
    {
        // 弹出二维码
        let callback = cEvent.callback
        if (callback.params)
        {
            callback.params = getParamsObjByEvenetParams(
                callback.params,
                record
            );
        }
        drawQrcode({ callback: callback }, {}).then(res =>
        {
            console.log(res, '回调')
        })
    }
    else if (cEvent.methodName && cEvent.methodName == 'WebPrint')
    {
        // 打印网页处理单
        let webPrint = document.getElementById( "hc-form" );
        let newContent = webPrint.innerHTML;
        // 创建临时容器
        const printDiv = document.createElement("div");
        printDiv.innerHTML = newContent;
        // 创建隐藏页眉页脚的样式
        const printStyle = document.createElement("style");
        printStyle.innerHTML = `
            @page {
                size: auto;
                margin: 0mm; 
                width: auto;
            }
            body {
                margin: 5px;
            }
            .head-right {
                margin-bottom: 20px;
            }
            .formTable {
                padding-top: 20px;
            }
            .hc-col {
                width: 160px !important;
            }
        `;
        document.head.appendChild(printStyle);

        // 标记正在打印，隐藏原页面
        document.body.classList.add("printing");
        document.body.appendChild(printDiv);
        // 确保渲染完成
        requestAnimationFrame(() =>
        {
            window.print();
            // 打印完成，恢复原页面
            document.body.removeChild(printDiv);
            document.head.removeChild(printStyle);
            document.body.classList.remove("printing");
        });
    }
}

function gaiZhangDoc(popParams, otherObj)
{
    //获取盖章文件
    getFileDataList({
        parentUnid: popParams.unid,
    })
        .then((res) =>
        {
            if (res.result && res.result.data.length > 0)
            {
                //存在，打开fileData盖章文伯
                let item = res.result.data[res.result.data.length - 1];
                let filePath =
                    item.efileHastmFilepath == null ?
                        item.efileHasstampFilepath :
                        item.efileHastmFilepath;
                let fileName =
                    item.efileHastmFilename == null ?
                        item.efileHasstampFilename :
                        item.efileHastmFilename;

                console.log("-----盖章文件---------------")
                console.log(filePath);
                console.log("-----盖章文件---------------")

                if (
                    filePath.toLowerCase().indexOf(".ofd") != -1 ||
                    filePath.toLowerCase().indexOf(".pdf") != -1 ||
                    filePath.toLowerCase().indexOf(".gd") != -1 ||
                    fileName.toLowerCase().indexOf(".ofd") != -1 ||
                    fileName.toLowerCase().indexOf(".pdf") != -1 ||
                    fileName.toLowerCase().indexOf(".gd") != -1
                )
                {
                    if (
                        window.HC_config.VUE_APP_OPEN_OFD
                    )
                    {
                        // ofd文件用福昕打开
                        window.open(
                            process.env.VUE_APP_PUBLIC_PATH + "zxfw/foxitofd.html?unid=" +
                            popParams.unid +
                            "&type=filedata"
                        );
                    } else
                    {
                        if (
                            filePath.toLowerCase().indexOf(".ofd") != -1 ||
                            filePath.toLowerCase().indexOf(".gd") != -1 ||
                            fileName.toLowerCase().indexOf(".ofd") != -1 ||
                            fileName.toLowerCase().indexOf(".gd") != -1
                        )
                        {
                            //ofd文件用数科打开
                            // window.open(process.env.VUE_APP_PUBLIC_PATH + "zxfw/ofd.html?unid=" + popParams.unid);
                            window.open(`/zxfw/ofdview.html?file=${popParams.unid}`)
                        }
                        if (
                            filePath.toLowerCase().indexOf(".pdf") != -1 ||
                            fileName.toLowerCase().indexOf(".pdf") != -1
                        )
                        {
                            window.open("/showpdf?unid=" + popParams.unid);
                            // router.push({
                            //     path: "/showpdf",
                            //     query: {
                            //         unid: popParams.unid
                            //     }
                            // })
                        }
                    }
                } else
                {
                    if (filePath == null)
                    {
                        editZBToGZDocV2(
                            VUE_APP_BASE_API,
                            "",
                            item.unid,
                            popParams.unid,
                            "",
                            "",
                            popParams.bookmark,
                            "",
                            popParams.moduleName,
                            store.getters.userInfo.personCommonname,
                            popParams.ycHongTou
                        );
                    }
                    else
                    {
                        console.log("------盖章----------")
                        console.log("------盖章----------")
                        editGZDocV2(
                            VUE_APP_BASE_API,
                            "",
                            item.unid,
                            popParams.unid,
                            "",
                            "",
                            popParams.bookmark,
                            "",
                            popParams.moduleName,
                            store.getters.userInfo.personCommonname,
                            undefined,
                            popParams.sealData
                        );
                    }
                }
            } else
            {
                //不存在打开正文，并添加保存标识
                getWordFilesList({
                    parentUnid: popParams.unid,
                }).then((res) =>
                {
                    if (res.result && res.result.data.length > 0)
                    {
                        var item = res.result.data[res.result.data.length - 1];
                        editGWToGZDocV2(
                            VUE_APP_BASE_API,
                            "",
                            item.unid,
                            popParams.unid,
                            "",
                            "",
                            popParams.bookmark,
                            "",
                            popParams.moduleName,
                            store.getters.userInfo.personCommonname,
                            popParams.ycHongTou,
                            popParams.sealData
                        );


                        //定时器每3秒发送一次请求
                        let interval = setInterval(function ()
                        {
                            getGaiZhangDoc(popParams, interval, otherObj);
                        }, 3000);
                    } else
                    {
                        Message.error("未上传正文，请先上传正文");
                    }

                });
            }

        })
        .catch((err) =>
        {
            Message.error("未找到文件");
        });
}

function getGaiZhangDoc(popParams, interval, otherObj)
{
    let isYyy = false;
    if (typeof popParams.unid == "undefined" || popParams.unid == "0")
    {
        clearInterval(interval);
        return;
    }
    store.getters.userInfo.roleKey.forEach((item) =>
    {
        if (item.roleName == "用印员")
        {
            isYyy = true;
        }
    });
    if (isYyy)
    {
        getFileDataList({
            parentUnid: popParams.unid,
        }).then((res) =>
        {
            if (res.result && res.result.data.length > 0)
            {
                let item = res.result.data[0];
                if (
                    item.efileHasstampFilepath != null ||
                    item.efileHastmFilepath != null
                )
                {
                    otherObj.reaLoadForm(); //刷新表单 隐藏盖章按钮
                    clearInterval(interval);
                }
            }
        }).catch(err =>
        {
            clearInterval(interval);
        });
    }
    else
    {
        clearInterval(interval);
    }
}

//生成pdf并上传
function uploadPdf(p_FormData)
{
    // 创建promise
    return new Promise((resolve, reject) =>
    {
        // html转pdf
        let fill = null;
        html2Canvas(document.querySelector("#pdfDom"), {
            allowTaint: true,
            useCORS: true, // canvas.toDataUrl() 图片跨域问题  添加这个设置
        }).then(function (canvas)
        {
            console.log("---------生成处理单--------------")
            const contentWidth = canvas.width;
            const contentHeight = canvas.height;
            console.log("canvasHeight" + contentHeight);
            const pageHeight = (contentWidth / 592.28) * 841.89;
            console.log("pageHeight" + pageHeight);
            let leftHeight = contentHeight;
            let position = window.HC_config.VUE_PDF_MARGIN_TOP || 0;
            const imgWidth = 595.28;
            const imgHeight = (592.28 / contentWidth) * contentHeight;
            const pageData = canvas.toDataURL("image/jpeg", 1.0);
            const PDF = new JsPDF("", "pt", "a4");
            if (leftHeight < pageHeight)
            {
                PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
            } else
            {
                while (leftHeight > 0)
                {
                    PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
                    leftHeight -= pageHeight;
                    position -= 841.89;
                    if (leftHeight > 0)
                    {
                        PDF.addPage();
                    }
                }
            }
            fill = PDF.output("datauristring");
            console.log(fill);
            const filepdf = dataURLtoFile(
                fill,
                (p_FormData.bt || "") + (window.HC_config.VUE_PDF_POSTFIX || "处理单.pdf")
            );
            const formData = new FormData();
            formData.append("file", filepdf);
            formData.append("relationUnid", p_FormData.unid);
            formData.append("moduleName", p_FormData.moduleName);
            formData.append("type", "formpdf");
            //上传
            openUpload(formData, (progress) =>
            {
                // this.$emit("AttachmentViewProgressUpdate", progress);
            })
                .then((res) =>
                {

                    resolve(res);
                })
                .catch((error) =>
                {
                    reject(error);
                })
                .finally(() => { });
        });
    });

}

/**
 *  cs 2024-7-18 编辑正文
 * @param {*} popParams
 */
function writeDoc(cEvent, record)
{
    let popParams;
    if (cEvent.eventProps)
    {
        popParams = getParamsObjByEvenetParams(
            cEvent.eventProps,
            record
        );
    } else
    {
        popParams = {};
    }
    getWordFilesList({
        parentUnid: popParams.unid,
    })
        .then((res) =>
        {
            let item;
            if (res.result && res.result.data.length > 0)
            {
                item = res.result.data[res.result.data.length - 1];
            }

            if (popParams.readOnly === true)
            {
                if (res.result && res.result.data.length > 0)
                {
                    if (item.suffix == "docx" || item.suffix == "doc" || item.attachPath.indexOf("doc") > -1 || item.attachPath.indexOf("docx") > -1 || item.suffix == "wps")
                    {
                        if (isUserWPS)
                        {
                            //打开只读正文
                            viewDocument(
                                VUE_APP_BASE_API,
                                item.unid,
                                ""
                            );
                        }
                        else
                        {
                            //只读打开在线链接
                            openWpsOnlineLink(popParams.unid, popParams.moduleName, "read", 0);
                        }
                    }
                    else
                    {
                        let zwUrl = getDownloadUrl(item.unid);
                        let urlParams = {
                            file: zwUrl,
                            filename: "正文.pdf",
                        };
                        let herf = buildPDFPreviewUrl(urlParams);
                        window.open(herf);
                    }
                } else
                {
                    Message.info("很抱歉，该文件没有正文");
                }
            } else
            {
                if (typeof item != "undefined" && item.state == 1)
                {
                    //文件已锁，不是当前办理人给提示，依然可以打开只读
                    if (item.lockUserName != store.getters.userInfo.personCommonname)
                    {
                        let lockname = item.lockUserName;
                        if (
                            item.lockUserName == undefined ||
                            item.lockUserName == ""
                        )
                        {
                            lockname = "他人";
                        }
                        Message.info("文件正在被（" + lockname + "）编辑，处于锁定状态，如需修改请联系运维人员或管理员解锁", true);
                        //文件已锁，不是当前办理人给提示，依然可以打开只读
                        if (isUserWPS)
                        {
                            //打开只读正文
                            viewDocument(
                                VUE_APP_BASE_API,
                                item.unid,
                                ""
                            );
                        }
                        else
                        {
                            //只读打开在线链接
                            openWpsOnlineLink(popParams.unid, popParams.moduleName, "read", 0);
                        }
                    } else
                    {
                        if (isUserWPS)
                        {
                            //以编辑模式打开正文
                            editDoc(popParams, res);
                        }
                        else
                        {
                            //编辑模式打开在线链接
                            openWpsOnlineLink(popParams.unid, popParams.moduleName, "write", 0);
                        }
                    }

                } else
                {
                    if (isUserWPS)
                    {
                        //以编辑模式打开正文
                        editDoc(popParams, res);
                    }
                    else
                    {
                        //编辑模式打开在线链接
                        openWpsOnlineLink(popParams.unid, popParams.moduleName, "write", 0);
                    }
                }
            }

        })
        .catch((err) =>
        {
            console.log(err)
            Message.error("未找到文件");
        });
}

/**
 * cs 2023-1-9
 * 查看正文
 * @param {} popParams
 */
async function checkDoc(popParams)
{
    //首先查询是否有盖章正文
    try
    {
        //盖章正文列表
        let gzDocListRes = await getFileDataList({
            parentUnid: popParams.unid,
        })
        //判断是否有盖章正文
        if (gzDocListRes.result && gzDocListRes.result.data.length > 0)
        {
            let item = gzDocListRes.result.data[gzDocListRes.result.data.length - 1];
            let filePath =
                item.efileHastmFilepath == null ?
                    item.efileHasstampFilepath :
                    item.efileHastmFilepath;
            let fileName =
                item.efileHastmFilename == null ?
                    item.efileHasstampFilename :
                    item.efileHastmFilename;
            if (
                filePath.toLowerCase().indexOf(".ofd") != -1 ||
                filePath.toLowerCase().indexOf(".pdf") != -1 ||
                filePath.toLowerCase().indexOf(".gd") != -1 ||
                fileName.toLowerCase().indexOf(".ofd") != -1 ||
                fileName.toLowerCase().indexOf(".pdf") != -1 ||
                fileName.toLowerCase().indexOf(".gd") != -1
            )
            {
                if (
                    window.HC_config.VUE_APP_OPEN_OFD
                )
                {
                    var agent = localStorage.getItem('agentOS')
                    if (agent && agent == 'window')
                    {
                        if (filePath.toLowerCase().indexOf(".pdf") != -1 || fileName.toLowerCase().indexOf(".pdf") != -1)
                        {
                            let url = getFileDataDownloadUrl(popParams.unid);

                            let urlParams =
                            {
                                file: url,
                                filename: popParams.bt || "最新发文",
                            };
                            let herf = buildPDFPreviewUrl(urlParams);
                            window.open(herf);
                        }
                        else
                        {
                            // ofd文件用福昕打开
                            window.open(
                                process.env.VUE_APP_PUBLIC_PATH + "zxfw/foxitofd.html?unid=" +
                                popParams.unid +
                                "&type=filedata"
                            );
                        }
                    }
                    else
                    {
                        let gzfilePath = getFileDataDownloadUrl(popParams.unid);
                        let markText = store.getters.userInfo.personCommonname + '\n ' + formatDate(new Date(), '{y}-{m}-{d}');
                        gzfilePath = window.btoa(gzfilePath);
                        let addWaterMarkTxt = encodeURI(
                            `${markText},10,10,30,20,仿宋_GB2312,14,FF0000,all,1,20,20;${markText},10,100,30,20,仿宋_GB2312,14,FF9900,all,1,20,20`
                        );
                        addWaterMarkTxt = decodeURI(addWaterMarkTxt);
                        let link = document.createElement("a");
                        link.href = `kpofd://openUrl=${gzfilePath}&fCompUnVisible=open,save,saveas,print,snapshot,hand,uploadfile,clipprint,selecttext&AddWaterMarkTxt=${addWaterMarkTxt}`;
                        link.click();
                    }
                }
                else
                {
                    if (
                        filePath.toLowerCase().indexOf(".ofd") != -1 ||
                        fileName.toLowerCase().indexOf(".ofd") != -1
                    )
                    {

                        //ofd文件用数科打开
                        // window.open(process.env.VUE_APP_PUBLIC_PATH + "zxfw/ofd.html?unid=" + popParams.unid);
                        window.open(`/zxfw/ofdview.html?file=${popParams.unid}&isGzzw=true`)
                    }
                    else if (filePath.toLowerCase().indexOf(".gd") != -1 || fileName.toLowerCase().indexOf(".gd") != -1)
                    {
                        //gd文件下载后自动打开
                        let requestParams = {
                            url: getFileDataDownloadUrl(popParams.unid),
                            method: "get",
                            responseType: 'blob'
                        };

                        //执行请求
                        request(requestParams)
                            .then((res) =>
                            {
                                if (res instanceof Blob)
                                {
                                    download(res, fileName);
                                }
                                else if (res.data instanceof Blob)
                                {
                                    download(res.data, fileName);
                                }
                            })
                    }
                    else if (
                        filePath.toLowerCase().indexOf(".pdf") != -1 ||
                        fileName.toLowerCase().indexOf(".pdf") != -1
                    )
                    {
                        let url = getFileDataDownloadUrl(popParams.unid);
                        let urlParams = {
                            file: url,
                            filename: popParams.bt || "最新发文",
                        };
                        let fileUrl = buildPDFPreviewUrl(urlParams);
                        window.open(fileUrl);
                    }

                }
            }
            else
            {
                //打开只读正文
                viewDocument(
                    VUE_APP_BASE_API,
                    item.unid,
                    ""
                );
            }
        }
        else
        {
            Message.info("很抱歉，该文件没有盖章正文")
        }
    }
    catch (err)
    {

    }
}


function dataURLtoFile(dataurl, filename)
{
    var arr = dataurl.split(",");
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--)
    {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

/**
 * cs 2022-4-4 执行自定义事件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 */
function executeEvent(event, cEvent, record, otherObj)
{
    if (
        cEvent.methodName
    )
    {
        let params = JSON.stringify(cEvent.eventProps);
        let fn = cEvent.methodName + "('" + params + "')";
        eval(fn);
    } else
    {
        let actionstr = cEvent.eventActions;
        if (actionstr && record)
        {
            if (record.constructor == Object)
            {
                for (let k in record)
                {
                    let recordItem = record[k];
                    if (actionstr.indexOf("@" + k) > -1)
                    {
                        actionstr = actionstr.replace("@" + k, recordItem);
                    }
                }
            }
        }
        eval(actionstr);
    }
}

/**
 * cs 2022-4-4 导出事件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 */
function exportEvent(event, cEvent, record, otherObj)
{
    //重新组装参数，根据@符号进行替换
    let params = getParamsObjByEvenetParams(
        cEvent.params,
        record
    );
    let requestParams = {
        url: cEvent.path,
        method: cEvent.methodName,
        responseType: 'blob'
    };
    if (cEvent.methodName.toLowerCase() == "post")
    {
        requestParams.data = {
            ...params,
            queryMap: otherObj.queryMap
        }
    } else
    {
        requestParams.params = {
            ...params,
            queryMap: otherObj.queryMap
        }
    }
    let fileName = params.fileName || new Date().getTime() + ".xlsx";
    //执行请求
    request(requestParams)
        .then((res) =>
        {
            if (res instanceof Blob)
            {
                download(res, fileName);
            }
            else if (res.data instanceof Blob)
            {
                download(res.data, res.fieldName || fileName);
            }
        })
}

/**
 * cs 2022-4-4 请求事件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 * @returns
 */
function requestEvent(event, cEvent, record, otherObj)
{
    //重新组装参数，根据@符号进行替换
    let params = getParamsObjByEvenetParams(
        cEvent.params,
        record,
    );
    if (otherObj && otherObj.callParams)
    {
        params = getParamsObjByEvenetParams(
            params,
            otherObj.callParams,
        )
    }

    if (params && params.needCheck)
    {
        //需要做表单检验
        let isRule = checkForm({
            fieldsList: otherObj.fieldsList,
            formParam: params
        }, {
            subList: otherObj.subList || [],
            subListData: params.subListData || []
        },
            otherObj.attachmentList
        )
        if (!isRule)
        {
            //验证不通过,中断请求
            return
        }
    }
    let requestParams = {
        url: cEvent.path,
        method: cEvent.methodName
    };
    if (cEvent.methodName.toLowerCase() == "post")
    {
        requestParams.data = params
    } else
    {
        requestParams.params = params
    }

    //执行请求
    request(requestParams)
        .then((res) =>
        {
            let oldOtherObj;
            let curRecord = res.result;
            if (requestParams.url == "/flow/func/writeNotion")
            {
                if (otherObj.reaLoadNotionData)
                {
                    //刷新阅文意见
                    otherObj.reaLoadNotionData(params.type || params.noton);
                }
            }
            if (cEvent.callback)
            {
                if (cEvent.callback.isOldRecord)
                {
                    clickEvent(cEvent.callback, record, otherObj);

                }
                else
                {
                    clickEvent(cEvent.callback, res.result, otherObj);
                }

            }
            if (res.result && res.result.event)
            {
                if (res.result.parentObj && typeof (res.result.parentObj) == 'string')
                {
                    oldOtherObj = otherObj;
                    let expand = res.result.parentObj.split(".");
                    if (expand.length != 0)
                    {
                        for (let str of expand)
                        {
                            otherObj = otherObj[str];
                        }
                    }
                }
                curRecord = res.result;
                if (res.result.customRecord && typeof (res.result.customRecord) == 'string')
                {
                    let expand = res.result.customRecord.split(".");
                    if (expand.length != 0)
                    {
                        curRecord = otherObj;
                        for (let str of expand)
                        {
                            // 判断为函数还是对象
                            if (typeof curRecord[str] == "function")
                            {
                                curRecord = curRecord[str]();
                            }
                            else
                            {
                                curRecord = curRecord[str]
                            }
                        }
                    }
                }
                if (otherObj && otherObj.reLoadFs && window.HC_config.VUE_APP_FSANDFORM)
                {
                    otherObj.reLoadFs(res.result.event, otherObj)
                }
                else
                {
                    clickEvent(res.result.event, curRecord, otherObj);
                }
            }
            if (res.result && res.result.printFlag && res.result.printUrl)
            {
                let httpUrl = localStorage.getItem("local_server_ip") || window.HC_config.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API
                var fileUrl = `${httpUrl}/rygl/file/review?glunid=${res.result.printUrl}`;
                var origin = window.location.origin

                let urlParams = {
                    file: fileUrl,
                    filename: "任免表.pdf",
                };
                const previewUrl = buildPDFPreviewUrl(urlParams);
                let pdfUrl = `${origin}${previewUrl}`;
                const iframeEl = document.createElement('iframe')
                iframeEl.class = 'iframe'
                iframeEl.style.position = 'fixed'
                iframeEl.style.zIndex = -99
                iframeEl.src = pdfUrl
                document.querySelector('body').append(iframeEl)
                const documentEl = iframeEl.contentDocument;
                documentEl.body.innerHTML = iframeEl.innerHTML
                setTimeout(() =>
                {
                    iframeEl.contentWindow.print()
                }, 2000)
                return
            }
            //post 请求需要提示
            if (res.message && cEvent.methodName.toLowerCase() != "get")
            {
                if (res.message != "")
                {
                    Message.success(res.message);
                }
            }
            // else
            // {
            //     if (!res.result || !res.result.event)
            //     {
            //         Message.success(res.message);
            //     }
            // }

            // 后端传递executeJs为true时，则执行js
            if (res.result && res.result.executeJs)
            {
                eval(res.result.executeJs)
            }

            // 后端传递cancelReloadView为true时，则取消刷新操作
            if (res.result && res.result.cancelReloadView)
            {
                return
            }
            if (otherObj.reaLoadView)
            {
                //刷新视图 视图的事件 会存在刷新视图的方法
                otherObj.reaLoadView();
            }
            // if (otherObj.reaLoadFs)
            // {
            //     //刷新视图 fs视图的事件 会存在刷新fs视图的方法
            //     otherObj.reaLoadFs();
            // }


        })
}

/**
 * cs 2022-4-4 上传文件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 */
function fileUpLoadEvent(event, cEvent, record, otherObj)
{
    const chunkSize = 1024 * 1024;
    let params = getParamsObjByEvenetParams(cEvent.eventProps, record);

    console.log(params, "【上传参数】");
    let inputDom = document.createElement("input");
    inputDom.type = "file";
    let multiple = params && params.multiple && Boolean(params.multiple);
    let webkitdirectory = params && params.webkitdirectory && Boolean(params.webkitdirectory);
    inputDom.multiple = multiple;
    inputDom.webkitdirectory = webkitdirectory;

    inputDom.onchange = () =>
    {
        let file = inputDom.files[0];
        var formdata = new FormData();
        //判断文件是否大于10M如果大于采用分片上传的方式
        if (webkitdirectory || (file.size < (chunkSize * 10) || !cEvent.m_ChunkUrl))
        {
            if (webkitdirectory)
            {
                let files = Array.from(inputDom.files);
                if (files.length !== 0)
                {
                    files.forEach(file =>
                    {
                        formdata.append('files', file);
                    });
                }
            }
            else
            {
                formdata.append("file", file);
            }
            // for (let key in params) {
            //     formdata.append(key, params[key]);
            // }
            if (otherObj.paramsMap)
            {
                params = {
                    ...otherObj.paramsMap,
                    ...params,
                }
            }

            console.time("【文件上传时间】");
            request({
                url: cEvent.methodName,
                method: "post",
                params: params,
                data: formdata,
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
            })
                .then((res) =>
                {
                    console.timeEnd("【文件上传时间】");
                    Message.success(res.message);
                    //操作成功后刷新视图，比如删除重新加载列表
                    // that.$bus.$emit("callBackgetViewData");

                    if (cEvent.callback)
                    {
                        clickEvent(cEvent.callback, res.result, otherObj);
                    }

                    if (res.result && res.result.event)
                    {
                        if (res.result.parentObj && typeof (res.result.parentObj) == 'string')
                        {
                            let expand = res.result.parentObj.split(".");
                            if (expand.length != 0)
                            {
                                for (let str of expand)
                                {
                                    otherObj = otherObj[str];
                                }
                            }
                        }
                        if (otherObj && otherObj.reLoadFs && window.HC_config.VUE_APP_FSANDFORM)
                        {
                            otherObj.reLoadFs(res.result.event, otherObj)
                        }
                        else
                        {
                            clickEvent(res.result.event, res.result, otherObj);
                        }
                    }

                    // 后端传递executeJs为true时，则执行js
                    if (res.result && res.result.executeJs)
                    {
                        eval(res.result.executeJs)
                    }

                    // 后端传递cancelReloadView为true时，则取消刷新操作
                    if (res.result && res.result.cancelReloadView)
                    {
                        return
                    }

                    if (otherObj.reaLoadView)
                    {
                        otherObj.reaLoadView();
                    }
                })
        }
        else
        {
            let hash = new Date().getTime() + "" + Math.floor(Math.random() * 1000);
            const chunkSize = 1024 * 1024;
            const totalChunks = Math.ceil(file.size / chunkSize);
            let chunk = 0;
            // const fileChunks = [];
            // for (let i = 0; i < totalChunks; i++)
            // {
            //     const start = i * chunkSize;
            //     const end = Math.min(file.size, start + chunkSize);
            //     const chunk = file.slice(start, end);
            //     fileChunks.push({ chunk, start, end, index: i, totalChunks });
            // }
            // let chunks = fileChunks.length;

            //添加上传记录
            let uploadLogItem = {
                url: cEvent.m_ChunkUrl,//上传地址
                params: JSON.parse(JSON.stringify(params)),//上传参数
                fileName: file.name,//文件名称
                fileSize: file.size,//文件大小
                progress: 0,//进度
                totalChunks: totalChunks,// 总片数
                chunk: chunk,//已上传片数
                state: 0,// 状态 0 正在上传 1 暂停 2 上传完毕
                file: file, //文件本地 持久化时会舍弃
                hash: hash,//上传记录唯一id
            }
            store.commit("uploadLog/addLog", uploadLogItem);//添加记录
            store.dispatch("uploadLog/starUpload", hash);//开始上传
        }
    }
    inputDom.click();
}

//文件转base64
function file2Base64(P_File, P_FileSize)
{
    return new Promise(async (resolve, reject) =>
    {
        const limitSize = window.HC_config.VUE_YWYJ_UPLOAD_FILE_SIZE || 1024;
        if (P_FileSize > limitSize * 1024 && P_File.type.includes('image'))
        {
            //压缩的大小，可自定义 2000kb
            P_File = await imageConversion.compressAccurately(P_File, limitSize);
            console.log("压缩后的文件", P_File.size);
        }

        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(P_File);
        reader.onload = function ()
        {
            imgResult = reader.result;
        };
        reader.onerror = function (error)
        {
            reject(error);
        };
        reader.onloadend = function ()
        {
            resolve(imgResult);
        };
    });
}

/**
 * cs 2022-4-4 改变控件
 * @param {*} event
 * @param {*} cEvent
 * @param {*} record
 * @param {*} otherObj
 */
function controlEvent(event, cEvent, record, otherObj)
{
    console.log("改变控件--->cEvent", cEvent);
    console.log("改变控件--->record", record);
    console.log("改变控件--->otherObj", otherObj);
    if (cEvent.eventProps)
    {
        //深拷贝 避免修改愿数据
        let copyEventProps = JSON.parse(JSON.stringify(cEvent.eventProps));
        let param = {};
        copyEventProps.forEach(element =>
        {
            param[element.fieldName] = element.value
        });
        //替换@后的值
        param = getParamsObjByEvenetParams(param, record);
        console.log("改变控件--->param", param);
        console.log("改变控件--->copyEventProps", copyEventProps);
        copyEventProps.forEach(element =>
        {
            if (param[element.fieldName] != null)
            {
                if (param[element.fieldName].constructor == Number)
                {
                    element.value = param[element.fieldName];
                }
                else if (param[element.fieldName].constructor == String)
                {
                    if (param[element.fieldName].indexOf("@") != 0)
                    {
                        element.value = param[element.fieldName];
                    }
                    else
                    {
                        element.value = "";
                    }
                }
                else
                {
                    element.value = param[element.fieldName];
                }
            } else
            {
                element.value = "";
            }
        })
        console.log("更新字段", copyEventProps);
        if (otherObj.editFieldsList)
        {
            otherObj.editFieldsList(copyEventProps);
        }
        //cs2024-11-23 兼容修改第一个表单
        if (otherObj.oldOtherObj)
        {
            if (otherObj.oldOtherObj.editFieldsList)
            {
                otherObj.oldOtherObj.editFieldsList(copyEventProps);
            }
        }

        if (cEvent.callback)
        {
            console.log("改变控件--->cEvent.callback", cEvent.callback);
            console.log("更新的参数数据", otherObj.getFormParam ? otherObj.getFormParam() : record);
            clickEvent(cEvent.callback, otherObj.getFormParam ? otherObj.getFormParam() : record, otherObj);
        }
    }
}

/**
 * cs 2022-3-9
 * 事件处理
 * @param {} event 事件数据
 * @param {*} record 表单或试图数据可能是[String,Array,Object]
 * @param {*} otherObj 其他参数方便后续配置
 * @returns
 */
export function clickEvent(event, record, otherObj)
{
    console.log("-------执行事件调度--------")
    console.log(event.btnEvent, record, otherObj);
    let cEvent = event.btnEvent || event;
    if (!cEvent)
    {
        console.error("------事件为空--------")
        return
    }

    if (typeof record == "function")
    {
        //如果是方法,则执行方法获取数据
        record = record();
    }
    if (typeof otherObj == "function")
    {
        //如果是方法则执行方法获取数据
        otherObj = otherObj();
    }
    let eventLog = {
        nr: JSON.stringify(cEvent)
    }

    // appendEventLog(eventLog).then(res => {

    // })

    console.log(cEvent.eventType);
    switch (cEvent.eventType)
    {
        case "POP_EVENT":
            //弹出表单或视图
            popEvent(event, cEvent, record, otherObj);
            break;
        case "LINK_EVENT":
            //链接
            linkEvent(event, cEvent, record, otherObj);
            break;
        case "MESSAGEBOX_EVENT":
            //按钮弹窗事件
            messageboxEvent(event, cEvent, record, otherObj);
            break;
        case "MODAL_EVENT":
            //编辑打开动态组件并回调
            modalEvent(event, cEvent, record, otherObj);
            break;
        case "EXECUTE_EVENT":
            //回调自定义函数名
            executeEvent(event, cEvent, record, otherObj);
            break;
        case "EXPORT_EVENT":
            //导出事件
            exportEvent(event, cEvent, record, otherObj);
            break;
        case "REQUEST_EVENT":
            //事件请求
            requestEvent(event, cEvent, record, otherObj);
            break;
        case "FILE_UPLOAD":
            //上传文件事件
            fileUpLoadEvent(event, cEvent, record, otherObj);
            break;
        case "CONTROL_EVENT":
            //改变控件
            controlEvent(event, cEvent, record, otherObj);
            break;
        case "MESSAGE_EVENT":
            //消息提示
            messageEvent(event, cEvent, record, otherObj);
            break;
        default:
            // 默认代码块
            console.error("----错误的事件类型----")
    }
}
